/*
 * Copyright 2018 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.paboo.chart.decode;

import com.google.gson.Gson;
import org.paboo.codec.Base64;
import org.paboo.utils.LoggerFactoryUtils;
import org.paboo.utils.ResponseUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;

@RestController
public class DecodeController {

    private LoggerFactoryUtils logger = LoggerFactoryUtils.getInstance().load(DecodeController.class);

    //
    @RequestMapping(value = "/decode", method = RequestMethod.POST)
    public ResponseEntity<byte[]> handleControllerExecution(@RequestBody(required = false) String requestStr) {

        if (!StringUtils.hasText(requestStr)) {
            logger.info("Error JSON is <" + requestStr + ">");
            return ResponseUtils.sendErrorOverJSON(HttpStatus.BAD_REQUEST, "Not found decode content!");
        }

        Gson gson = new Gson();

        BufferedImage image = DecodeUtils.processStream(new ByteArrayInputStream(Base64.decode(requestStr)));
        if (image == null) {
            return ResponseUtils.sendErrorOverJSON(HttpStatus.BAD_REQUEST, "Bad Image! The image you uploaded could not be decoded, or was too large." +
                    "  Go \"Back\" in your browser and try another image.");
        }
        try {
            return ResponseUtils.sendOkContent(MediaType.TEXT_PLAIN, gson.toJson(DecodeUtils.processImage(image)).getBytes());
        } finally {
            image.flush();
        }
    }
}
